<template>
  <div class="timetableListContainer" v-if="classinfo">
    <el-dialog
      :visible.sync="isShow"
      custom-class="el-dialog-bg"
      :close-on-click-modal="modalclose"
      :before-close="handleClose"
    >
      <div slot="title" class="panel_title">
        <span>{{classinfo.className||"未知"}}({{classinfo.classNo}})</span>
        <span>排课列表</span>
        <span
          @click="entertimetable"
          style="float: right;margin-right: 0.5rem;font-size: 0.16rem;color:rgb(31, 160, 254);cursor: pointer;"
        >课程表</span>
      </div>
      <!--双师-->
      <div class="double-teacher" v-if="classinfo.courseType==4">
        <el-row>
          <el-col :span="16">
            <span>{{classinfo.courseName}}</span>&nbsp;
            <span>余额支付</span>&nbsp;
            <span>订单号：</span>&nbsp;
            <span>{{classinfo.feiboClassOrderId}}</span>
          </el-col>
          <el-col :span="4">已约{{dateNum}}节/共{{totallesson}}节</el-col>
          <el-col :span="4">
            <span
              @click="DateTeacher(null)"
              v-if="dateNum==0||dateNum != totallesson"
              style="cursor:pointer;float: right;border:1px solid #DDDDDD;padding:0.01rem 0.2rem;"
            >约名师</span>
          </el-col>
        </el-row>
      </div>

      <div class="timetableList">
        <div class="tablecss">
          <table style="width:100%;" cellpadding="0" cellspacing="0">
            <thead>
              <tr>
                <th v-if="classinfo.courseType!=2">课程序号</th>
                <th style="width:2.4rem;">上课时间</th>
                <th v-if="classinfo.courseType!=4">课程库名称</th>
                <th>教师</th>
                <th>助教</th>
                <th>教室</th>
                <th v-if="classinfo.courseType==4">名师</th>
                <th style="width:2.3rem;" v-if="classinfo.courseType==4">名师上课时间</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody v-if="timetableList.length>0">
              <tr v-for="li,index in timetableList">
                <td
                  v-if="classinfo.courseType!=2"
                  align="center"
                  class="classroomInfo"
                  :data-clipboard-text="li.classroomInfo"
                >第{{index+1+(param.currPage-1)*param.pageSize}}次课</td>
                <td align="center">
                  {{li.startTime.split(' ')[0]}}&nbsp;({{getMyDay(li.startTime.split(' ')[0])}})&nbsp;
                  {{li.startTime.split(' ')[1]}}-{{li.endTime.split(' ')[1]}}
                </td>
                <td align="center" v-if="classinfo.courseType!=4">{{li.courseName}}</td>
                <td align="center">{{li.teacherUserName}}</td>
                <td align="center">{{li.assisUserName}}</td>
                <td align="center">{{li.classroomName}}</td>
                <td align="center" v-if="classinfo.courseType==4">{{li.feiboTeacherName}}</td>
                <td align="center" v-if="classinfo.courseType==4">
                  <template v-if="li.feiboTeacherName">
                    {{li.realFeiboStartTime.split(' ')[0]}}&nbsp;
                    {{li.realFeiboStartTime.split(' ')[1]}}-{{li.realFeiboEndTime.split(' ')[1]}}
                  </template>
                </td>
                <td align="center">
                  <span v-if="li.attendMode==1">已上课</span>
                  <span v-else-if="li.attendMode==2||li.attendMode==0">未上课</span>
                </td>
                <td align="center">
                  <!--双师课,-->
                  <span
                    v-if="classinfo.courseType==4 && li.isDate && li.enableFeiboSyllabus==1 && (li.feiboSyllabusTeacherId==null||li.feiboSyllabusTeacherId==0)"
                    @click="DateTeacher(li)"
                    style="color:#1FA0FE;cursor: pointer;"
                  >约名师</span>
                  <span
                    @click="adjustment(li)"
                    style="color:#1FA0FE;cursor: pointer;"
                    v-if="(li.attendMode==2||li.attendMode==0)&&(li.feiboSyllabusTeacherId==null||li.feiboSyllabusTeacherId==0) && hasApi('adjustCourseThistime') && hasApi('contrapositiveCourse')"
                  >调整</span>
                  <span style="color:#666666;cursor: not-allowed;" v-else>调整</span>
                  <span
                    v-if="(li.attendMode==2||li.attendMode==0) && hasApi('classsyllabusDelete') && hasOneDay(li)"
                    @click="deleteSyllabus(li)"
                    style="color:#1FA0FE;cursor: pointer;"
                  >&nbsp;删除</span>
                </td>
              </tr>
            </tbody>
            <tbody v-else>
              <tr>
                <td colspan="11" align="center">暂无数据</td>
              </tr>
            </tbody>
          </table>
        </div>
        <el-pagination
          class="page"
          layout="total, sizes, prev, pager, next, jumper"
          :current-page.sync="currPage"
          @size-change="pageSizeChange"
          @current-change="tabledisplayChangePage"
          :page-size.sync="param.pageSize"
          :total="totalCount"
        ></el-pagination>
      </div>
    </el-dialog>

    <!--调整列表-->
    <el-dialog
      :visible.sync="showdialog"
      custom-class="el-dialog-bg2"
      :close-on-click-modal="modalclose"
      :before-close="handleClose2"
    >
      <div slot="title" class="panel_title" v-if="curCourse">
        <span>第{{curCourse.orderBy}}次课</span>
        <span>
          (
          {{curCourse.startTime.split(' ')[0]}}&nbsp;
          {{curCourse.startTime.split(' ')[1]}}
          -
          {{curCourse.endTime.split(' ')[1]}}
          )
        </span>
      </div>
      <div class="adjustment">
        <div class="dialog">
          <div class="item">
            <span class="spanlabel">调整类型</span>
            <el-select
              v-model="adjusttypetext"
              ref="selectAdjusttype"
              @change="changetype"
              placeholder="请选择"
            >
              <el-option
                v-for="item in adjusttype"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
          <div class="item" v-if="showtype2">
            <span style="color:red;"></span>
            <span class="spanlabel">与</span>
            <el-select v-model="classtimestext" ref="selectclassSyllabusId" placeholder="请选择课次">
              <el-option
                v-for="item in classtimeslist"
                :key="item.classSyllabusId"
                :label="item.orderBy"
                :value="item.classSyllabusId"
              >
                <span style="float: left">{{ item.date }}&nbsp;{{ item.sTime }}-{{ item.eTime }}</span>
                <span style="float: left">&nbsp;{{ item.courseName }}</span>
              </el-option>
            </el-select>
            <span class="spanlabel">课次对调</span>
          </div>
          <div class="item" v-if="showtype1">
            <span class="spanlabel">调整时间</span>
            <!--日期-->
            <el-date-picker
              v-model="timedate.datestr"
              type="date"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              placeholder="选择日期"
            ></el-date-picker>
            <!--开始时间-->
            <el-time-select
              style="width:1.5rem;"
              v-model="timedate.sTime"
              @change="changeStartTime"
              :picker-options="{start: campusTime.minStartTime,step: '00:05',end: campusTime.maxEndTime}"
            ></el-time-select>
            <!--结束时间-->
            <el-time-select
              disabled
              style="width:1.5rem;"
              v-model="timedate.eTime"
              :picker-options="{start: campusTime.minStartTime,step: '00:05',end: campusTime.maxEndTime}"
            ></el-time-select>
          </div>
          <div class="item" v-if="showtype1">
            <span class="spanlabel">调整教师</span>
            <el-select
              v-model="adjustteachertext"
              filterable
              ref="selectTeacher"
              placeholder="调整教师"
            >
              <el-option
                v-for="item in teacherlist"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId"
              ></el-option>
            </el-select>
          </div>
          <div class="item" v-if="showtype1">
            <span class="spanlabel">调整教室</span>
            <el-select
              v-model="adjustclassroomtext"
              filterable
              ref="selectClassRoom"
              placeholder="调整教室"
            >
              <el-option
                v-for="item in classroomtlist"
                :key="item.classroomId"
                :label="item.name"
                :value="item.classroomId"
              ></el-option>
            </el-select>
          </div>
        </div>
      </div>
      <div slot="footer" class="footer-btn">
        <el-button @click="adjustbtnCancel" class="btnCancel">取 消</el-button>
        <el-button @click="adjustbtnOk" class="btnOk">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from "vuex"; //先要引入
import Clipboard from "clipboard";

let vm;
export default {
  //props:["classinfo"],
  data() {
    return {
      tableData: {
        datatitle: {},
        datacontent: []
      },
      timedate: {
        datestr: "",
        sTime: "",
        eTime: "",
        spanmin: 0
      },
      classinfo: null,
      modalclose: false,
      showdialog: false,
      showtype1: true, //调整本次显示
      showtype2: false, //与其他课程对调显示
      adjusttypetext: "",
      curCourse: null,
      currPage: 1,
      adjusttype: [
        { name: "调整本次", value: "1" },
        { name: "与其他课次对调", value: "2" }
      ],
      classtimestext: "",
      classtimeslist: [],
      adjustteachertext: "",
      adjustclassroomtext: "",
      conflictcourse: [],

      /** 限制日期**/
      pickerOptions: {},
      campusTime: { minStartTime: "07:00", maxEndTime: "21:00" }
    };
  },
  methods: {
    /**初始化数据**/
    initata() {
      this.showtype1 = true;
      this.showtype2 = false;
      this.adjusttypetext = "1";
      this.curCourse = null;
      this.classtimestext = "";
      this.currPage = 1;
      if (config.timtlist.length > 0) {
        this.campusTime.minStartTime = config.timtlist[0].time || "07:00";
        this.campusTime.maxEndTime =
          config.timtlist[config.timtlist.length - 1].time || "17:30";
      }
    },
    /**判断是否在一天之内 */
    hasOneDay(item) {
      // 课节时间
      let itemTime = new Date(item.startTime + ":00").getTime();
      // 获取当前日期
      let currentDate = new Date().getTime();
      if (itemTime > currentDate + 24 * 3600) {
        return true;
      }
      return false;
    },
    /**删除排课课节 */
    deleteSyllabus(item) {
      this.$confirm("此操作将删除该课节, 是否继续?", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
        .then(() => {
          api
            .classsyllabusDelete({ id: item.classSyllabusId })
            .then(function(data) {
              if (data.resultCode == 2000) {
                vm.$message({
                  message: "删除成功",
                  type: "success"
                });
                vm.$store.dispatch("timetableList/gettimetableList", vm.param);
                if (vm.$parent.menu == 1) {
                  vm.$parent.searchData(1); //刷新父组件
                } else {
                  vm.$parent.selectOverClassData(1);
                }
              } else {
                vm.$message.error(data.message);
              }
            });
        })
        .catch(() => {});
    },
    getMyDay(str) {
      let date = new Date(str);
      var week;
      if (date.getDay() == 0) week = "周日";
      if (date.getDay() == 1) week = "周一";
      if (date.getDay() == 2) week = "周二";
      if (date.getDay() == 3) week = "周三";
      if (date.getDay() == 4) week = "周四";
      if (date.getDay() == 5) week = "周五";
      if (date.getDay() == 6) week = "周六";
      return week;
    },
    pageSizeChange(val) {
      vm.param.pageSize = val;
      vm.$store.dispatch("timetableList/gettimetableList", vm.param);
    },
    tabledisplayChangePage(val) {
      vm.param.currPage = val;
      vm.$store.dispatch("timetableList/gettimetableList", vm.param);
    },
    setClassInfo(data) {
      this.classinfo = data;
    },
    handleClose() {
      vm.param.currPage = 1;
      this.$store.dispatch("timetableList/hidetimetableListPanel");
      this.initata();
    },
    handleClose2() {
      this.showdialog = false;
      this.initata();
    },
    /**
     * 课节开始时间调整
     */
    changeStartTime(val) {
      this.timedate.eTime = tool.calculEndTime(val, this.timedate.spanmin);
    },
    /**
     * 课程调整
     */
    adjustment(row) {
      this.curCourse = row;

      this.adjusttypetext = "1";
      this.timedate.datestr = row.startTime.split(" ")[0];
      this.timedate.sTime = row.startTime.split(" ")[1];
      this.timedate.eTime = row.endTime.split(" ")[1];
      this.timedate.spanmin =
        tool.hourConversionMin(this.timedate.eTime) -
        tool.hourConversionMin(this.timedate.sTime);
      this.adjustclassroomtext = row.classroomId;
      this.adjustteachertext = row.teacherUserId;

      this.classtimeslist = [];
      for (let i = 0; i < this.timetableList.length; i++) {
        if (this.timetableList[i].attendMode == 2)
          this.classtimeslist.push({
            classSyllabusId: this.timetableList[i].classSyllabusId,
            orderBy: this.timetableList[i].orderBy,
            courseName: this.timetableList[i].courseName,
            date: this.timetableList[i].startTime.split(" ")[0],
            sTime: this.timetableList[i].startTime.split(" ")[1],
            eTime: this.timetableList[i].endTime.split(" ")[1]
          });
      }
      this.showdialog = true;
    },
    /**
     * 类型切换
     */
    changetype(val) {
      if (val == 1) {
        this.showtype1 = true;
        this.showtype2 = false;
      } else if (val == 2) {
        this.showtype1 = false;
        this.showtype2 = true;
      }
    },
    /**
     * 调整对话框取消按钮
     */
    adjustbtnCancel() {
      this.showdialog = false;
      this.initata();
    },
    /**
     * 调整对话框确定按钮
     */
    adjustbtnOk() {
      let type = this.adjusttypetext;

      if (type == "1") {
        //调整本次

        let paras = {
          classSyllabusId: this.curCourse.classSyllabusId,
          classId: this.curCourse.classId,
          courseId: this.curCourse.courseId || "",
          startTime: this.timedate.datestr + " " + this.timedate.sTime,
          endTime: this.timedate.datestr + " " + this.timedate.eTime,
          teacherUserId: this.$refs.selectTeacher.value || "",
          classroomId: this.$refs.selectClassRoom.value || "",
          orderBy: this.curCourse.orderBy,
          attendMode: this.curCourse.attendMode,
          assisUserId: this.curCourse.assisUserId,
          classHour: this.curCourse.classHour
        };
        let rules = [];
        //					let todaystart = "08:00";
        //					let todayend = "21:00";

        if (this.timedate.eTime > this.campusTime.maxEndTime) {
          rules.push({
            judge: null,
            focus: null,
            tips: "结束时间不能大于校区设置时间"
          });
        }

        if (!tool.validate(rules)) {
          return;
        }

        api.adjustCourseThistime(paras).then(function(data) {
          if (data.result == "操作成功") {
            //刷新排课列表
            vm.$message({
              message: "调课成功",
              type: "success"
            });
            vm.$store.dispatch("timetableList/gettimetableList", {
              classId: vm.curCourse.classId,
              courseId: vm.curCourse.coursePackageId
            });
            vm.initata();
          }
        });
      } else if (type == "2") {
        //与其他课次对调

        if (this.classtimestext == "") {
          vm.$message({
            message: "请选择课次",
            type: "warning"
          });
          return;
        }

        let paras = {
          firstSyllabus: this.curCourse.classSyllabusId,
          secondSyllabus: this.classtimestext
        };
        api.contrapositiveCourse(paras).then(function(data) {
          if (data.result == "操作成功") {
            vm.$message({
              message: "调课成功",
              type: "success"
            });
          }
          //刷新排课列表
          vm.$store.dispatch("timetableList/gettimetableList", {
            classId: vm.curCourse.classId,
            courseId: vm.curCourse.coursePackageId
          });
          vm.initata();
        });
      }
      this.showdialog = false;
    },
    /**
     * 进入课程表
     */
    entertimetable() {
      this.$router.push({
        path: "/education/timetable_manage",
        query: { classId: this.classinfo.classId }
      });
      this.$store.dispatch("timetableList/hidetimetableListPanel");
    },
    /**约外教**/
    DateTeacher(li) {
      //alert(vm.dateNum)
      let list = [];
      if (li) {
        list.push(li);
      } else {
        vm.datetimetableList.forEach(ele => {
          if (
            vm.classinfo.courseType == 4 &&
            ele.isDate &&
            ele.enableFeiboSyllabus == 1 &&
            (ele.feiboSyllabusTeacherId == null ||
              ele.feiboSyllabusTeacherId == 0)
          )
            list.push(ele);
        });
      }

      let param = {
        teacher: {
          visible: true,
          data: { classObj: vm.classinfo, courseObj: list, type: li ? 2 : 1 }
        },
        syllabus: { visible: false },
        classorder: { visible: false }
      };
      this.$emit("showOrderForeignSyllabuslist", param);
    }
  },
  computed: {
    ...mapState({
      isShow: state => state.timetableList.timetableListDialog,
      teacherlist: state => state.commondata.teacherlist,
      classroomtlist: state => state.commondata.classroomlist,
      totalCount: state => state.timetableList.totalCount,
      param: state => state.timetableList.param
    }),
    ...mapGetters("timetableList", {
      timetableList: "gettimetableList"
    }),
    totallesson: function() {
      let num = vm.classinfo.syllabusEndNum - vm.classinfo.syllabusStartNum + 1;
      return vm.classinfo.feiboSyllabusNum || num;
    },
    dateNum: function() {
      let num = 0;
      for (let i = 0; i < vm.timetableList.length; i++) {
        if (
          vm.timetableList[i].feiboSyllabusTeacherId != null &&
          vm.timetableList[i].feiboSyllabusTeacherId != 0
        ) {
          num++;
        }
      }
      return num;
    },
    datetimetableList: function() {
      let list = [];
      for (let i = 0; i < vm.timetableList.length; i++) {
        if (
          vm.timetableList[i].isDate &&
          (vm.timetableList[i].feiboSyllabusTeacherId == null ||
            vm.timetableList[i].feiboSyllabusTeacherId == 0)
        ) {
          list.push(vm.timetableList[i]);
        }
      }

      return list;
    }
  },
  mounted() {
    vm = this;
    this.initata();
  },
  created: function() {
    this.pickerOptions.disabledDate = function(time) {
      let todaydate = new Date(new Date().getTime() - 1000 * 60 * 60 * 24);
      let today = new Date(tool.DateToString(todaydate, "yyyy-MM-dd"));
      let enddate = new Date(vm.classinfo.endTime);

      if (time <= today || time >= enddate) {
        return true;
      }
      return false;
    };
    //创建粘贴板对象
    new Clipboard(".classroomInfo");
  }
};
</script>

<style lang="scss">
@import "@/style/module/utils.scss";
.timetableListContainer {
  .footer-btn {
    .btnOk {
      width: 1.6rem;
      height: 0.4rem;
      font-size: 0.16rem;
      background: #3885f8;
      color: #ffffff;
      border-radius: 0.1rem;
    }
    .btnCancel {
      width: 1.6rem;
      height: 0.4rem;
      font-size: 0.16rem;
      background: #ffffff;
      color: #333333;
      border-radius: 0.1rem;
    }
  }
  .timetableList {
    width: 100%;
    padding: 0 0.31rem 0.3rem 0.31rem;
    .showMore {
      width: 100%;
      padding: 0.2rem 0;
      text-align: center;
      cursor: pointer;
      font-size: 0.16rem;
      color: #666666;
      margin: 0 auto;
    }
  }
  .adjustment {
    width: 100%;
    max-height: 3rem;
    padding: 0 0.31rem 0rem 0.31rem;
    .item {
      width: 100%;
      height: 0.6rem;
      line-height: 0.5rem;
    }
  }
  /**自定义对话框标题样式**/
  .panel_title {
    padding: 0.23rem 0.31rem 0.23rem 0.31rem;
    font-size: 0.22rem;
    font-family: "microsoft yahei";
    color: #333333;
  }
  /**双师**/
  .double-teacher {
    width: 100%;
    height: 0.3rem;
    line-height: 0.3rem;
    padding: 0rem 0.31rem;
    font-size: 0.16rem;
    margin-bottom: 0.2rem;
  }
  /**
		 * 自定义对话框样式
		 */
  .el-dialog-bg {
    background: #ffffff;
    width: 12rem;
    border-radius: 0.1rem;
    .el-dialog__header {
      padding: 0px;
    }
    .el-dialog__body {
      padding: 0px !important;
    }
    .el-dialog__footer {
      padding: 0.3rem;
      .footer-btn {
        width: 100%;
        text-align: center;
      }
    }
  }

  .el-dialog-bg2 {
    background: #ffffff;
    width: 7rem;
    border-radius: 0.1rem;
    .el-dialog__header {
      padding: 0px;
    }
    .el-dialog__body {
      padding: 0px !important;
    }
    .el-dialog__footer {
      padding: 0.3rem;
      .footer-btn {
        width: 100%;
        text-align: center;
      }
    }
  }
}
</style>